import {
    isFunction,
    isFunctionComponent
} from "./utils"
import updateNodeElement  from './updateNodeElement'
export function mountElement(virtualDOM, container) {
    if (isFunction(virtualDOM)) {
        mountComponent(virtualDOM, container)
    } else {
        mountNativeElement(virtualDOM, container)
    }
}

export function mountComponent(virtualDOM, container) {
    let newVirtualDOM
    if (isFunctionComponent(virtualDOM)) {
        newVirtualDOM = buildFunctionComponent(virtualDOM)
    } else {
        newVirtualDOM = buildClassComponent(virtualDOM)
    }
    mountElement(newVirtualDOM, container)
}

function buildFunctionComponent(virtualDOM) {
    return virtualDOM.type(virtualDOM.props || {})
}

function buildClassComponent(virtualDOM) {
    const component = new virtualDOM.type(virtualDOM.props)
    const newVirtualDOM = component.render()
    newVirtualDOM.component = component
    return newVirtualDOM
}
// 虚拟DOM对象
function mountNativeElement(virtualDOM, container) {
    const newEl = createDOMElement(virtualDOM)
    container.appendChild(newEl)
    const component = virtualDOM.component
    if (component) {
        component.setDOM(newEl)
    }
}
// 创建DOM元素
function createDOMElement(virtualDOM) {
    let newEl = null
    if (virtualDOM.type === 'text') {
        newEl = document.createTextNode(virtualDOM.props.textContent)
    } else {
        newEl = document.createElement(virtualDOM.type)
        updateNodeElement(newEl, virtualDOM)
    }

    virtualDOM.children.forEach(child => {
        mountElement(child, newEl)
    })
    newEl.__virtualDOM = virtualDOM
    return newEl
}